package com.woniuxy.service.impl;

import com.rabbitmq.client.MessageProperties;
import com.woniuxy.po.Mail;
import com.woniuxy.service.Producer;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author: 马宇航
 * @Do: 生产者消费者模式的service实现类
 * @DateTime: 22/07/06/0006 下午 3:16
 * @Component: 成都蜗牛学苑
 **/
@Service
public class ProducerImpl implements Producer {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public void sendMail(String pcqueue, Mail mail) {
        //设置那个队列来接收消息
        rabbitTemplate.setDefaultReceiveQueue(pcqueue);
        //如果没有交换机，默认“” 空串交换机，队列名称就是routingkey！
        rabbitTemplate.convertAndSend("aa",pcqueue,mail);
        //设置响应回调，如果找不到交换机，则回调ack为false
        rabbitTemplate.setConfirmCallback(confirmCallback);
    }
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            //交换机回调给生产者的消息 如果交换机收到消息，返回true，否则
            if(ack){
                System.out.println("-------------------ConfirmCallback,发送到交换机成功------------------------");
                System.out.println("发送成功，进行业务操作....");
                if (correlationData!=null){
                    //交换机返回给生产者的消息
                    ReturnedMessage returned = correlationData.getReturned();
                    System.out.println("发送成功"+"correlationData全局id为："+correlationData.getId());
                }
            }else {
                System.out.println("-------------------ConfirmCallback,发送到交换机失败------------------------");
                if (correlationData!=null){
                    System.out.println("发送失败"+"correlationData全局id为："+correlationData.getId());
                }
                System.err.println("失败原因："+cause);
            }
        }
    };
}
